package com.miao.im.biz;

import com.miao.im.common.Message;
import com.miao.im.common.annotation.MessageCommand;
import com.miao.im.common.enums.Command;
import com.miao.im.model.HeartBeatModel;
import com.miao.im.model.MsgIdResponseModel;
import com.miao.im.server.session.SessionContext;
import com.miao.im.server.session.SessionManager;
import com.miao.im.support.IdManager;
import com.miao.im.support.handler.AbstractMessageHandler;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import reactor.core.publisher.Mono;

/**
 * @Auther: miaoguoxin
 * @Date: 2021/3/3 16:35
 * @Description:
 */
@Component
@MessageCommand(value = Command.GENERATE_ID)
@Slf4j
public class MsgIdRequestHandler extends AbstractMessageHandler<HeartBeatModel.Heartbeat> {
    @Autowired
    private IdManager idManager;

    @Override
    protected void doRead(HeartBeatModel.Heartbeat body, Message message) {

    }

    @Override
    protected Mono<Void> doDispatch(HeartBeatModel.Heartbeat body, Message message, SessionContext sessionContext) {
        // log.info("收到获取消息号请求:{}", System.currentTimeMillis());
        return Mono.just(idManager.generateId())
                .flatMap(id -> {
                    MsgIdResponseModel.MsgIdResponse msgIdResponse = MsgIdResponseModel.MsgIdResponse.newBuilder()
                            .setMsgId(id)
                            .build();
                    return Mono.just(msgIdResponse);
                })
                .doOnSuccess(msgIdResponse -> {
                    Message response = Message.writeResponse(message.getVersion(), message.getSequence(),
                            Command.GENERATE_ID.getCode(), msgIdResponse.toByteArray());
                    SessionManager.send(sessionContext, response);
                }).then();
    }

}
